package struct.tree.iter;

import struct.tree.node.Node;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: 柒月
 * @date: 2025/5/2 下午10:14
 * @version: 1.0
 */
public class PreorderTraversal {

    public static int[] preorderRecursion(Node root) {
        List<Integer> result = new LinkedList<>();
        preorderRecursion(root, result);
        return result.stream().mapToInt(i -> i).toArray();
    }

    private static void preorderRecursion(Node root, List<Integer> result) {
        if (root == null) {
            return;
        }
        result.add(root.data);
        preorderRecursion(root.left, result);
        preorderRecursion(root.right, result);
    }

    public static int[] preorderIterative(Node root) {
        List<Integer> result = new LinkedList<>();
        Deque<Node> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            result.add(node.data);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return result.stream().mapToInt(i -> i).toArray();
    }
}
